<template>
  <el-dialog :title="formData.id?'编辑客户':'添加客户'" :visible="showDialog" @close="closeFn">
    <el-form ref="form" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="经纪">
        <el-select v-model="formData.agent">
          <el-option v-for="item in agentsList " :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item label="微信">
        <el-input v-model="formData.wechat" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" type="textarea" :rows="4" resize="none" />
      </el-form-item>
      <el-form-item label="封面">
        <upImg ref="img1" />
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="end">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="closeFn">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import upImg from '@/components/UpImg'
import { addClients, editClinets } from '@/api/client'
export default {
  components: { upImg },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    agentsList: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      formData: {
        agent: '', // 属于哪个经纪的 id 值
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '', // 描述
        image: ''// 图片
      },
      rules: {
        name: [{ required: true, message: '该项不能为为空', trigger: 'blur' }],
        desc: [{ required: true, message: '该项不能为为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async submit() {
      // 校验
      await this.$refs.form.validate()
      //   腾讯云返回的网站赋值在formdata的image上
      this.formData.image = this.$refs.img1.dialogImageUrl || this.$refs.img1.imgUrl // 封面
      if (this.formData.id) {
        // 编辑客户
        this.$message.success('编辑成功')
        await editClinets(this.formData)
      } else {
        // 调用函数
        this.$message.success('添加成功')
        await addClients(this.formData)
      }
      //   更新函数
      this.$emit('update')
      //   关闭
      this.closeFn()
    },
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空数据
      this.formData = {
        agent: '', // 属于哪个经纪的 id 值
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '', // 描述
        image: ''// 图片
      }
      // 清除校验规则
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
